package com.pengtu.gsj.dao.system;

import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import com.pengtu.gsj.dao.hibernate.HibernateDao;
import com.pengtu.gsj.entity.app.Role;
import com.pengtu.gsj.entity.app.User;

/**
 * 用户对象的泛型DAO类.
 * 
 * @author calvin
 */
@Repository
public class UserDao extends HibernateDao<User, String> {
	
	@Autowired
	private SessionFactory sessionFactory;
	
	 @Override
	public User get(String id) {
		User user = super.get(id);
		if(null != user){
			this.initProxyObject(user.getRoleList());
		}
		return user;
	}

	/**
	 * getListByOrgRole:
	 * 适用:
	 * @param orgId
	 * @param roleDExaminer1
	 * @return 
	 * @exception 
	 * @since  1.0.0
	*/
	@SuppressWarnings("unchecked")
	public List<String> getListByOrgRole(String orgId, String roleName) {
		String sql = "select t.id from T_APP_USER t,t_app_role r,r_app_userrolerelation ur," +
				"t_app_employe e,t_app_organization o where t.delflag='0' and r.delflag='0' " +
				"and e.delflag='0' and o.delflag='0' and ur.userid=t.id and ur.roleid=r.id " +
				"and e.id=t.id and e.orgid=o.id and r.rolename='"+roleName+"' and o.id='"+orgId+"'";
		return this.getSession().createSQLQuery(sql).list();
	}

	
	/**
	 * 
	 * hasAnyRole:
	 * 适用:当前用户是否拥有该角色
	 * @param roleName
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public boolean hasAnyRole(String roleName,User user){
		if(null == user){
			return false;
		}
		List<Role> rs = user.getRoleList();
		for(Role r:rs){
			if(r.getRoleName().equals(roleName)){
				return true;
			}
		}
		return false;
	}
	/**
	 * 根据登录名查找该用户姓名
	 * @param string
	 * @param username
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String findName(String username){
		String sql = "select e.name from User t,Employe e "
			+"where t.id=e.id and t.username=?";
		Query query = this.getSession().createQuery(sql);
		query.setParameter(0, username);
		query.setCacheable(true);//启用查询缓存
		List<String> list = query.list();
		if(list.size() != 0){
			return list.get(0);
		}
		return "";
	}
	
	/**
	 * 根据用户名查询用户
	 * getUserByUsername:
	 * 适用:
	 * @param username
	 * @return 
	 * @exception 
	 * @since  1.0.0
	 */
	public User getUserByUsername(String username) {
		Session session = sessionFactory.openSession();
		String hql = "from User where username='"+username+"'";
		Query query = session.createQuery(hql);
		return (User) query.list().get(0);
	}
	
	public User getUser(String username){
		return findUniqueBy("username", username);
	}
	
	public List<User> checkEmail(String email){
		String hql ="from User e where e.email='"+email+"'";
		return find(hql);
	}
}
